package com.wephone.Student.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.wephone.Student.R;
import com.wephone.Student.bean.CareUserListResponse;
import com.wephone.Student.bean.data.CareUserInfoData;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.PullToRefreshView;
import com.wephone.Student.util.PullToRefreshView.OnFooterRefreshListener;
import com.wephone.Student.util.PullToRefreshView.OnHeaderRefreshListener;
import com.wephone.Student.util.RoundImageView;

public class FocusActivity extends BaseActivity {
	private static long backClickTime = -1;
	private PullToRefreshView pullToRefreshListView;
	private ListView listView;
	private ListViewAdapter adapter;
	private List<CareUserInfoData> results = new ArrayList<CareUserInfoData>();
	public static boolean needRefresh = true;

	private MyResponseHandler getHandler(){
		MyResponseHandler handler = new MyResponseHandler(FocusActivity.this,CareUserListResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					CareUserListResponse res = (CareUserListResponse)response;
					
					if(res.getData().size()<Constants.PAGE_SIZE){
						adapter.hasMore = false;
					}else{
						adapter.pageIdx++;
					}
					results.addAll(res.getData());
					adapter.notifyDataSetChanged();
				}
			}
		};
		return handler;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_focus);
		
		init();
	}
	
	private void init(){
		listView = (ListView)findViewById(R.id.listview);
		adapter = new ListViewAdapter();
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new ListView.OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Bundle bundle = new Bundle();
				bundle.putSerializable("userData", results.get(arg2).getuInfo());
				startActivity(new Intent(getApplicationContext(),UserInfoDetailActivity.class).putExtras(bundle));
			}});
		
		pullToRefreshListView = (PullToRefreshView)findViewById(R.id.pull_refresh_listview);
		pullToRefreshListView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
			@Override
			public void onHeaderRefresh(PullToRefreshView view) {
				results.clear();
				adapter.hasMore = true;
				adapter.pageIdx = 1;
				
				RequestParams params = new RequestParams();
				params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
				params.put("Page", "1");
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				HttpClient.getInstance().get(Constants.API_GET_CARE_USER_LIST_URL, params, getHandler());
			}
		});
		pullToRefreshListView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
			@Override
			public void onFooterRefresh(PullToRefreshView view) {
				if(!adapter.hasMore){
					pullToRefreshListView.onFooterRefreshComplete();
					return;
				}
				RequestParams params = new RequestParams();
				params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
				params.put("Page", ""+adapter.pageIdx);
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				HttpClient.getInstance().get(Constants.API_GET_CARE_USER_LIST_URL, params, getHandler());
			}
		});
		
		FocusActivity.needRefresh = true;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		if(needRefresh || results.size()==0){
			needRefresh = false;
			
			findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
			results.clear();
			adapter.hasMore = true;
			adapter.pageIdx = 1;
			
			RequestParams params = new RequestParams();
			params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
			params.put("Page", "1");
			params.put("PageSize", ""+Constants.PAGE_SIZE);
			HttpClient.getInstance().get(Constants.API_GET_CARE_USER_LIST_URL, params, getHandler());
		}
	}
	
	private DisplayImageOptions options = new DisplayImageOptions.Builder()
    .showStubImage(R.drawable.default_user_logo)
    .showImageOnFail(R.drawable.default_user_logo)
    .bitmapConfig(Bitmap.Config.ARGB_8888)
    .cacheInMemory()
    .cacheOnDisc()
//    .displayer(new RoundedBitmapDisplayer(1000))
    .build();

	private class ListViewAdapter extends BaseAdapter{
		public int pageIdx = 1;
		public boolean hasMore = true;
		private SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		
		@Override
		public int getCount() {
			return results.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView==null){
				convertView = getLayoutInflater().inflate(R.layout.include_focus_list_item, null);
			}
			CareUserInfoData data = results.get(position);
			TextView itemName = (TextView)convertView.findViewById(R.id.item_name);
			itemName.setText(data.getuInfo().getuName());
			TextView itemCountry = (TextView)convertView.findViewById(R.id.item_country);
			itemCountry.setText(sdf.format(new Date(Long.parseLong(data.getuInfo().getuTS())*1000)));
			TextView universityText = (TextView)convertView.findViewById(R.id.item_university);
			universityText.setText(data.getuInfo().getuConstellation());
			TextView itemSign = (TextView)convertView.findViewById(R.id.item_signature);
			itemSign.setText(data.getuInfo().getuSign());
			
			TextView genderText = (TextView)convertView.findViewById(R.id.item_gender_text);
			ImageView genderImage = (ImageView)convertView.findViewById(R.id.item_gender);
			if(data.getuInfo().getuGender().equals("0")){
				genderImage.setImageResource(R.drawable.online_male);
				genderText.setText("男");
			}else{
				genderImage.setImageResource(R.drawable.online_female);
				genderText.setText("女");
			}
			
			if(!TextUtils.isEmpty(data.getuInfo().getuIcon())){
				RoundImageView itemImage = (RoundImageView)convertView.findViewById(R.id.item_image);
				String endStr = data.getuInfo().getuIcon().substring(data.getuInfo().getuIcon().lastIndexOf("."));
				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+data.getuInfo().getuIcon().replace(endStr, "_150_150"+endStr), itemImage, options);
//				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+data.getuInfo().getuIcon(), itemImage, options);
			}
			
//			//load more
//			if(position>=results.size()-1 && hasMore){
//				RequestParams params = new RequestParams();
//				params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
//				params.put("Page", ""+pageIdx);
//				params.put("PageSize", ""+Constants.PAGE_SIZE);
//				HttpClient.getInstance().get(Constants.API_GET_CARE_USER_LIST_URL, params, getHandler());
//			}
			return convertView;
		}		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		 if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			 long nowTime = System.currentTimeMillis();
				if(backClickTime<=0 || nowTime-backClickTime>2000){
					backClickTime = nowTime;
					Toast.makeText(getApplicationContext(), "再按一次 退出程序", Toast.LENGTH_SHORT).show();
				}else{
					finish();
				}
			return true; 
        }
        return super.onKeyDown(keyCode, event); 
	}
	
}
